package com.ly.controller;

import com.ly.pojo.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


@RestController
public class FileUploadController {
    @PostMapping("/upload")
    public Result<String> upload(@RequestParam("file") MultipartFile file) {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return Result.error("文件为空");
            }

            // 获取文件名
            String originalFilename = file.getOriginalFilename();

            originalFilename =  System.currentTimeMillis() + "_" + originalFilename;
            if (originalFilename == null || originalFilename.isEmpty()) {
                return Result.error("文件名为空");
            }

            // 确保目标目录存在
            File directory = new File("D:\\file");
            if (!directory.exists()) {
                directory.mkdirs();
            }

            // 拼接完整的文件路径
            File destFile = new File(directory, originalFilename);

            // 保存文件
            file.transferTo(destFile);

            return Result.success("url访问地址...");
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("文件上传失败: " + e.getMessage());
        }
    }
}

